<template>
  <div class="main">
    <img class="banner one" src="../../static/di tu yi/ditu_zuo.jpeg" alt="">
    <img class="banner two" src="../../static/di tu yi/ditu_youshang.jpeg" alt="">
    <img class="banner five" src="../../static/di tu yi/ditu_zuozhong.jpeg" alt="">
    <div class="header">
      <div v-for="(item, index) in btns" :key="index" class="btn" :class="{active: current === index}"
           @click="currentToogle(index)">{{ item }}
      </div>
    </div>
    <div class="card">
      <block v-if="current == 0">
        <div class="item_nav">
          <div class="label">
            <img src="../../static/images/biyenianyue.png" class="icon" alt="">
            关键词
          </div>
          <div class="value">
            <div class="value">
              <u--input
                placeholder="请输入关键词"
                border="none"
                inputAlign="right"
                placeholderStyle="font-size: 30rpx;"
                fontSize="30rpx"
                v-model="form.keyword"
              ></u--input>
            </div>
          </div>
        </div>
        <div class="item_nav" v-for="(item, key, index) in lists" :key="index">
          <div class="label">
            <img :src="`../../static/images/${item.imgStr}.png`" class="icon" alt="">
            {{ item.label }}
          </div>
          <div  class="value" @click="handleShowCLick(key, item.disabled)" style="position: relative;">
		   <div v-show="key === 'major' && form.subMajorExist === '1'" 
		     class="background-warning" >{{ ` &nbsp; &nbsp;  ${form.major}   &nbsp; &nbsp; `}}</div>
            <template v-if="key === 'major'">
              {{ form.major || form.subMajor || `请选择${item.label} ` }}
            </template>
            <template v-else>
              {{ form[key]['label'] || form[key] || `请选择${item.label}` }}
            </template>
            <img v-if="key !== 'major' && form[key]" class="icon"
                 :src="`../../static/images/${item.icon || 'buxian'}.png`" 
				 alt="" 
				 @click.stop="deleteFn(key)"/>
            <img v-else-if="key === 'major' && form[key] || key ==='major' && form.subMajor" class="icon" :src="`../../static/images/${item.icon || 'buxian'}.png`" alt="" @click.stop="deleteFn(key)">
          </div>
        </div>
      </block>
      <block v-else>
        <div class="import" @click="onDiscernHandle">
          <div class="ling"></div>
          <div class="ling"></div>
          <div class="ling"></div>
          <div class="roundContent">
            立即导入
          </div>
        </div>
      </block>
    </div>
    <div class="card_footer">
      <button class="btn" :class="{flag: flag}" @click="matching">超级匹配</button>
    </div>

    <!-- <div class="main_footer">
      <div class="item" v-for="(item, index) in mainFooterList" :key="index">
        <img v-if="item.icon" :src="`../../static/images/${item.icon}.png`" class="icon" alt=""/>
        {{ item.label == '余数' ? '余数:0/0' : item.label }}
      </div>
    </div> -->

    <cityPicker :cityShow="showhouseholdRegistration" :format="lists.householdRegistration.type"
                @confirm="actionSelect($event, 'householdRegistration')"
                @cancel="showhouseholdRegistration = false"></cityPicker>
    <cityPicker :cityShow="showworkLocation" :format="lists.workLocation.type"
                @confirm="actionSelect($event, 'workLocation')" @cancel="showworkLocation = false"></cityPicker>

    <u-picker ref="educationLevelPicker" :show="showeducationLevel" :columns="lists.educationLevel.list" keyName="label"
              @change="changeHandler($event, 'educationLevel')" @confirm="actionSelect($event, 'educationLevel')"
              @cancel="showeducationLevel = false"></u-picker>
    <u-picker ref="majorPicker" :show="showmajor" :columns="lists.major.list"
              @change="changeHandler($event, 'major')" @confirm="actionSelect($event, 'major')"
              @cancel="showmajor = false"></u-picker>
    <u-picker ref="recruitmentAgePicker" :show="showrecruitmentAge" :columns="lists.recruitmentAge.list"
              @change="changeHandler($event, 'recruitmentAge')"
              @confirm="actionSelect($event, 'recruitmentAge')" @cancel="showrecruitmentAge = false"></u-picker>
    <u-picker ref="settledPicker" :show="showsettled" :columns="lists.settled.list" keyName="label"
              @change="changeHandler($event, 'settled')" @confirm="actionSelect($event, 'settled')"
              @cancel="showsettled = false"></u-picker>
    <u-picker ref="companyNaturePicker" :show="showcompanyNature" :columns="lists.companyNature.list" keyName="label"
              @change="changeHandler($event, 'companyNature')" @confirm="actionSelect($event, 'companyNature')"
              @cancel="showcompanyNature = false"></u-picker>
    <u-toast ref="uToast"></u-toast>
  </div>

</template>

<script>
import professionalList from '@/utils/professional.js'
import {getQueryString} from '@/utils/index.js'
import cityPicker from '@/components/cityPicker/index'
import {login, getEducationList, getMajorList} from "@/api/user";

export default {
  components: {
    cityPicker
  },
  data() {
    return {
      token: uni.getStorageSync('AccessToken'),
      btns: ['手工录入', '导入简历'],
      current: 0,
      form: {
        educationLevel: "", // 学历
        major: '', // 专业
        subMajor: '', // 专业2
        recruitmentAge: '', // 年龄
        householdRegistration: '', //户籍
        workLocation: '', // 意向城市
        settled: '', // 落户意向
        companyNature: '', // 单位性质
        keyword: '', // 关键词
		subMajorExist: ''
      },
      showDegree: false,
      showeducationLevel: false,
      showmajor: false,
      showgender: false,
      showrecruitmentAge: false,
      showhouseholdRegistration: false,
      showworkLocation: false,
      showsettled: false,
      showcompanyNature: false,
      lists: {
        educationLevel: {
          label: '学历',
          imgStr: 'xueli',
          list: [
            []
          ],
          show: false,
        },
        major: {
          label: '专业',
          imgStr: 'zhuanye',
          list: [],
          show: false,
		  style: '; backgroud-color: red'
        },
        recruitmentAge: {
          label: '年龄',
          imgStr: 'nianling',
          list: [
            [18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
          ],
          show: false,
          deleteIcon: true
        },
        householdRegistration: {
          label: '户籍',
          imgStr: 'huji',
          list: [
            []
          ],
          show: false,
          city: true,
          type: ['province', 'city', 'district'],
          deleteIcon: true
        },
        workLocation: {
          label: '意向城市',
          imgStr: 'chengshi',
          list: [
            ["北京", "上海", "广州", "深圳", "杭州"]
          ],
          show: false,
          city: true,
          type: ['province'],
          deleteIcon: true
        },
        settled: {
          label: '落户意向',
          imgStr: 'chengshi',
          list: [
            [{
              label: '有',
              value: 1
            },
              {
                label: '无',
                value: 0
              }]
          ],
          show: false,
          deleteIcon: true
        },
        companyNature: {
          label: '单位性质',
          imgStr: 'chengshi',
          list: [
            [
              {label: "不限", value: 0},
              {label: "国家机关", value: 1},
              {label: "央企", value: 2},
              {label: "国企", value: 3},
              {label: "事业单位", value: 4},
              {label: "民营企业", value: 5},
              {label: "上市公司", value: 6}
            ]
          ],
          show: false,
          deleteIcon: true
        }
      },
      companyNature: '',
      settled: '',
      degree: '',
      mainFooterList: [],
      graduationYearMonthShow: false,
      dateValue: +new Date(),
      minDate: +new Date(1924, 1, 1),
      professionalLevel1: [],
      professionalLevel2: [],
      sessionKey: '',
      flag: false,
      fileList: [],
    };
  },
  created() {
    this.initProcessList();
    this.getEducationList();
  },
  onShow() {
    const Center_useitem = uni.getStorageSync('Center_useitem') || null
    if (Center_useitem) {
      const obj = JSON.parse(Center_useitem)
      for (let key in this.form) {
        if (obj[key]) {
          if (key === 'educationLevel') {
            const obj2 = this.lists.educationLevel.list[0].find(v => v.label === obj[key])
            this.form[key] = obj2 || ''
          } else {
            this.form[key] = obj[key]
          }
        }
      }
    }
  },
  mounted() {
  },
  onLoad() {
    uni.$on('updateProfessional', (data) => {
      if (!data.child) {
        this.form.major = data.professional
        this.form.subMajor = ''
      } else {
        this.form.subMajor = data.professional
        this.form.major = ''
      }
	  this.form.subMajorExist = '0'
    })
  },
  onHide() {
    localStorage.removeItem('Center_useitem')
  },
  methods: {
    async getEducationList() {
      const res = await getEducationList('edu_level')
      this.lists.educationLevel.list = [res.data.map(item => ({label: item.dictLabel, value: item.dictValue}))]
    },
    // 生成一个不会重复的 sessionkey
    generateSessionKey(length) {
      let chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
      let key = '';
      for (let i = 0; i < length; i++) {
        key += chars.charAt(Math.floor(Math.random() * chars.length));
      }
      return key;
    },
    getQueryString, // 获取参数信息
    initProcessList() {
      professionalList.forEach((item1, index1) => {
        let temp2 = [];
        this.professionalLevel1.push(item1.category);
        item1.children.forEach((item2, index2) => {
          temp2.push(item2.categoryName);
        });
        this.professionalLevel2[index1] = temp2;
      });

      // 选择器默认城市
      this.lists.major.list.push(this.professionalLevel1, this.professionalLevel2[0]);
    },
    changeHandler(e, key) {
      const {
        columnIndex,
        index,
        indexs,
        value,
        values,
        // 微信小程序无法将picker实例传出来，只能通过ref操作
        picker = this.$refs[`${key}Picker`],
      } = e;
      const multiColumnList = ['major']
      if (columnIndex === 0 && multiColumnList.includes(key)) {
        // 选择第一列数据时
        // 设置第二列关联数据
        picker.setColumnValues(1, this[`${key}Level2`][index]);
      }
    },
    handleShowCLick(key) {
      if (key === 'major') {
        if (!this.form.educationLevel) {
          this.$refs.uToast.show({
            type: 'default',
            title: '提示',
            message: "请先选择学历"
          })
          return
        }
        const educationLevel = this.form.educationLevel instanceof Array ? this.form.educationLevel[0].value : typeof this.form.educationLevel === 'string' ?  this.lists.educationLevel.list[0].find(item => item.label === this.form.educationLevel).value : this.form.educationLevel.value
        uni.navigateTo({
          url: `/pagesProfessional/index?params=${educationLevel}&major=${this.form.major}&subMajor=${this.form.subMajor}`
        })
        return
      }
      this[`show${key}`] = true;
    },
    currentToogle(num) {
      this.current = num
    },
    cancel() {
      this.form.degree = false;
    },
    async actionSelect(e, key) {
      this.form[key] = e.value instanceof Array ? (e.value[0] instanceof Object ? e.value[0].label : e.value.join('-')) : e.value;
      this[key] = e.value
      if (key === 'educationLevel') {
        this.form[key] = e.value[0]
        this.form.major = ''
        this.form.subMajor = ''
        uni.setStorageSync('searchMajor', '')
        // const {data} = await getMajorList(this[key][0].value)
        // this.lists.major.list = data;
      } else if (key === 'companyNature') {
        this.form[key] = e.value[0]
      }
      this[`show${key}`] = false
    },
    dateClose() {
      this.graduationYearMonthShow = false
    },
    dateConfirm(e) {
      this.form.graduationYearMonth = e.value
      this.dateClose()
    },
    async matching() {
      if (this.flag) return;
	  if (this.form.subMajorExist==='1') {
		this.$refs.uToast.show({
		  type: 'error',
		  icon: true,
		  title: '提示',
		  message: "导入专业未识别，请重新选择",
		  iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/error.png'
		})
		return;
	  }
      const that = this;
      try {
        await this.check(); // 校验函数
        // 判断是否登录，未登录调用接口登录
        that.flag = true
        const query = {}
        for (let key in this.form) {
          if (this.form[key]) {
            if (key === 'educationLevel') {
              query[key] = this.form[key].value
            }else if(key === 'householdRegistration' && this.form[key]){
			      	query[key] = JSON.stringify(this.form[key].split('-'))
			      	// {"pageNum": "1", "pageSize": "10", "major": "金融学", "recruitmentAge": "24", "householdRegistration": "河南信阳"}
			      }else if (key === 'companyNature') {
              query[key] = this.form[key].value
            } else {
              query[key] = this.form[key]
            }
          }
        }
        uni.setStorageSync('formData', JSON.stringify(query))
        uni.navigateTo({
          url: '/pagesDetail/index',
          success: () => {
            that.flag = false;
          }
        })
      } catch (error) {
        that.flag = false;
      }
    },
    check() {
      const optionalList = ['educationLevel', 'major']
      return new Promise((res, rej) => {
        for (let key in this.form) {
          if (!this.form[key] && optionalList.includes(key)) {
            if (key === 'major' && this.form.subMajor) {
              res(true)
              return;
            }
            this.$refs.uToast.show({
              type: 'error',
              icon: true,
              title: '提示',
              message: "学历和专业为必填项",
              iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/error.png'
            })
            rej(false)
          }
        }
        res(true)
      })
    },
    async getToken(code, sessionKey) {
      try {
        // 获取用户信息
        const res = await login({
          code, sessionKey
        })
        localStorage.setItem("AccessToken", res.data);
        // 修改当前页的 url 为当前页的 url
        // window.history.replaceState(null, null, window.location.href);
        this.flag = false;
        // this.matching();
      } catch (err) {
        this.flag = false;
      }
    },
    onDiscernHandle() {
      if (this.fileList.length !== 0) {
        return false;
      }
      const that = this
      uni.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['camera', 'album'], //从相册选择
        success: async (res) => {
          var imageSrc = res.tempFilePaths[0]
          const token = uni.getStorageSync('AccessToken');

          uni.showLoading({
            title: '加载中...',
            mask: true
          })
          uni.uploadFile({ //上传图片
            url: 'https://yanj.com.cn/wx/resume/upload', //开发者服务器 url
            filePath: imageSrc, //要上传文件资源的路径。
            fileType: 'image', //文件类型，image/video/audio
            name: 'file', //文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
            header: {
              Authorization: `Bearer ${token}`
            },
            success: (res) => { //接口调用成功的回调函数
              const data = JSON.parse(res.data).data
              for (let key in that.form) {
                if (data[key]) {
                  that.form[key] = data[key]
                }
              }
              uni.showToast({ //消息提示框
                title: '上传成功',
                icon: 'success',
                duration: 1000
              })
              this.current = 0
              uni.hideLoading();
            },
            fail: () => {
              // 接口调用失败
              uni.hideLoading();
            }
          });
        },

      });
    },
    deleteFn(key) {
      this.form[key] = ''
      if (key === 'major') {
        this.form.subMajor = ''
		this.form.subMajorExist = '0'
      }
    }
  },
};
</script>

<style lang="scss" scoped>
.main {
  position: relative;
  min-height: calc(96vh - 100rpx);
  padding-top: 15vh;
  font-size: 34rpx;
  overflow: hidden;
  // background-color: #eeeff3;
  box-sizing: border-box;

  .banner {
    position: absolute;
    width: 80rpx;
    height: 80rpx;
    overflow: hidden;

    &.one {
      left: 0;
      top: 0;
    }

    &.two {
      width: 100rpx;
      height: 150rpx;
      right: 0;
      top: 0;
    }

    &.three {
      width: 400rpx;
      height: 220rpx;
      left: 0;
      bottom: -80rpx;
    }

    &.fore {
      width: 300rpx;
      height: 200rpx;
      right: 0rpx;
      bottom: -70rpx;
    }

    &.five {
      width: 220rpx;
      height: 320rpx;
      left: 0;
      top: 350rpx;
    }
  }

  .header {
    display: flex;
    margin-left: -110rpx;
    margin-bottom: -50rpx;

    .btn {
      margin: 0 auto;
      width: 34%;
      height: 50rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      clip-path: polygon(13% 5%, 18% 0, 100% 0, 95% 22%, 85% 100%, 0 100%, 11% 11%);
      border-radius: 12rpx 0 0 12rpx;
      color: #FFFFFF;
      background-color: #bab6ff;
      transition: all .3s;

      &.active {
        background-color: #7665f9;
      }

      &:first-child {
        margin-right: 0;
      }

      &:last-child {
        margin-left: -20rpx;
      }

      &:active {
        background-color: #7665f9;
      }
    }
  }

  .card_footer {
    margin-top: -70rpx;

    .btn {
      padding: 0rpx 32rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      width: 77%;
      height: 70rpx;
      background-color: #7665f9;
      margin: 0 auto;
      margin-right: 24rpx;
      color: #FFFFFF;
      clip-path: polygon(11% 4%, 13% 0, 100% 0, 100% 100%, 2% 100%, 4% 81%, 6% 54%, 8.5% 14%, 9% 11%, 10% 7%);
      border-radius: 0 16rpx 16rpx 0;
      font-size: 34rpx;
      font-weight: 600;
      box-sizing: border-box;

      &.flag {
        background-color: #bab6ff;
      }

      &:active {
        background-color: #bab6ff;
      }
    }
  }

  .card {
    width: 95%;
    min-height: 65vh;
    margin: 0 auto;
    border-radius: 32rpx;
    padding: 32rpx;
    display: flex;
    flex-direction: column;
    background: rgba(238, 239, 248, .25);
    box-shadow: 10rpx 10rpx 20rpx rgba(236, 237, 245, .05);
    backdrop-filter: blur(5px);
    border-radius: 8px;
    padding: 100rpx 32rpx;
    box-sizing: border-box;
    clip-path: polygon(0 8%, 74% 8%, 77% 6%, 80% 2%, 83% 0, 100% 0, 100% 90%, 27% 90%, 24% 92%, 22% 95%, 18% 100%, 0 100%);

    .item_nav {
      flex: 1;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10rpx;
      border-bottom: 1rpx dotted #c8ccd2;

      &:last-child {
        border: none;
      }

      .label {
        display: flex;
        align-items: center;
        font-size: 32rpx;

        .icon {
          width: 50rpx;
          height: 50rpx;
        }
      }

      .value {
        flex: 1;
        display: flex;
        justify-content: flex-end;
        align-items: center;
        font-size: 30rpx;

        .icon {
          width: 60rpx;
          height: 60rpx;
          margin-left: -15rpx;
          margin-top: 2rpx;
        }
      }
    }

    .import {
      width: 300rpx;
      height: 300rpx;
      border-radius: 50%;
      position: relative;
      background: linear-gradient(125deg, rgb(118, 101, 249) 0%, rgb(186, 182, 255) 46%, rgb(238, 239, 243) 100%);
      margin: 100rpx auto;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;

      .ling {
        background: #c0b8ff;
        position: absolute;
        right: 80rpx;
        top: -30rpx;
        width: 10rpx;
        height: 30rpx;
        border-radius: 40rpx;
        transform: rotate(0deg);

        &:nth-child(2) {
          right: 50rpx;
          top: -20rpx;
          transform: rotate(25deg);
        }

        &:nth-child(3) {
          right: 20rpx;
          top: 0rpx;
          transform: rotate(65deg);
        }
      }

      .roundContent {
        color: #FFFFFF;
        font-size: 38rpx;
        font-weight: 600;
      }
    }
  }

  .main_footer {
    position: relative;
    display: flex;
    justify-content: space-around;
    align-items: center;
    z-index: 9;
    top: 80rpx;

    .item {
      display: flex;
      align-items: center;

      .icon {
        width: 50rpx;
        height: 50rpx;
      }
    }
  }
}

::v-deep .u-upload__wrap {
  justify-content: center;
}

.background-warning {
    position: absolute;
	right: 3%;
    top: 10;
    height: 100%;
    // width: 100%;
	color: #89CFF0;
	background-color: #89CFF0;
    z-index: -1;
	border-radius: 13px;
  }
</style>